﻿using Admin.CommonLib.Constants;
using Admin.CommonLib.Models.User;
using Newtonsoft.Json;
using Swimj.CommonLib.Base;
using Swimj.Core.Extensions;
using System.Net.Http.Json;

namespace Admin.RazorLib.Services
{
    public class UserService : IUserService
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public UserService(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }


        public async Task<PaginatedResult<UserInfoResponseDto>> QueryUsersByPage(UserSearchRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync(model.ToQueryString(ApiRoutes.User.QueryUsers));
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<PaginatedResult<UserInfoResponseDto>>(resultJson);
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<List<UserInfoResponseDto>>> QueryUsers(UserSearchRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync(model.ToQueryString(ApiRoutes.User.QueryUsers));
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<List<UserInfoResponseDto>>>(resultJson);
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<HttpResponseMessage> ExportTemplate()
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync($"/{ApiRoutes.User.ExportTemplateUser}");
                return response;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<HttpResponseMessage> ExportUsers(UserSearchRequestDto searchRequestDto)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync(searchRequestDto.ToQueryString(ApiRoutes.User.ExportUser));
                return response;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<UserInfoResponseDto>> CreateUser(UserEditRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.PostAsJsonAsync($"/{ApiRoutes.User.CreateUser}", model);
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<UserInfoResponseDto>>(resultJson);
                    }
                }

                return new Result<UserInfoResponseDto>();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<UserInfoResponseDto>> GetUser(Guid key)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync($"/{ApiRoutes.User.GetUser.Replace("{id}", key.ToString())}");
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<UserInfoResponseDto>>(resultJson);
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<UserInfoResponseDto>> UpdateUser(Guid key, UserEditRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.PutAsJsonAsync($"/{ApiRoutes.User.UpdateUser.Replace("{id}", key.ToString())}", model);
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<UserInfoResponseDto>>(resultJson);
                    }
                }

                return new Result<UserInfoResponseDto>();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<IList<UserImportResponseDto>>> ImportUsers(int importType, string fileName,
            Stream stream)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");

                var multipartFormDataContent = new MultipartFormDataContent();
                multipartFormDataContent.Add(new StreamContent(stream), "file", fileName);
                var response =
                    await httpClient.PostAsync($"{ApiRoutes.User.ImportUser}?importType={importType}",
                        multipartFormDataContent);

                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<IList<UserImportResponseDto>>>(resultJson);
                    }
                }

                return new Result<IList<UserImportResponseDto>>();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }
}